package com.mysoft.gfyx.marketdevelop.service.impl;

import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.util.MyStringUtil;
import com.mysoft.gfyx.marketdevelop.controller.dto.GetProcurementRequirementMobileRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.*;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteClueService;
import com.mysoft.gfyx.marketdevelop.service.DeveloperService;
import com.mysoft.gfyx.marketdevelop.service.LoadDataApiCommonService;
import com.mysoft.gfyx.marketdevelop.service.ProcurementRequirementService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProcurementRequirementServiceImp extends AppService implements ProcurementRequirementService {

    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private RemoteClueService remoteClueService;

    @Autowired
    private LoadDataApiCommonService loadDataApiCommonService;

    public FieldsSetting loadFields() {

        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("uuid");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_cooperator";
        fieldsSetting.getFields().add(new DataApiField("uuid", groupName, "RowID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "采购需求ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_name", groupName, "招标单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("title", groupName, "采购标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("data_source", groupName, "采购平台", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("status", groupName, "采购状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("bidding_service_category", groupName, "行业分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("publish_time", groupName, "发布时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("project_city", groupName, "项目地点", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("projects", groupName, "项目", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("has_added", groupName, "是否已添加过线索", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("ower", groupName, "联系人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("ower_mobile", groupName, "联系人电话", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("purchase_demand_cnt_1year", groupName, "关联招标", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise_cnt", groupName, "合作单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("end_time", groupName, "截止时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("purchase_amount", groupName, "采购金额", FieldType.Decimal));
        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        if (options.getOptions().getContext().get("id") == null || options.getOptions().getContext().get("id").toString().equals("")) {
            ListDataResult listDataResult = new ListDataResult();
            listDataResult.setData(new String[0]);
            return listDataResult;
        }
        String creditCode = options.getOptions().getContext().get("id").toString();
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT);
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());
        //dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, creditCode, DeveloperService.TABLE_PROCUREMENT_REQUIREMENT, BaseTjFilterDto.ASSOCIATE_NONE);
        List<Filter> filters = options.getOptions().getFilters();
        loadDataApiCommonService.setDefaultDeveloperWithoutInvestment(filters, creditCode);
        //loadDataApiCommonService.setDefaultDeveloper(filters, creditCode);
        dto.addFilterByLoadDataApi(filters, DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("publish_time");
        sort.setTable_name(DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        ListDataResult ListDataResult = this.setProceurementSpecialFields(res);

        return ListDataResult;
    }

    public ListDataResult setProceurementSpecialFields(BaseTjListResponseDto res) {
        ListDataResult result = new ListDataResult();
        ArrayList<Object> output = new ArrayList<>();

        if (res.getData().getList() == null || res.getData().getList().size() == 0) {
            result.setData(output);
            result.setTotal(0);
            return result;
        }

        ArrayList<String> purchasesId = new ArrayList<>();
        ArrayList<String> creditCodes = new ArrayList<>();
        res.getData().getList().forEach(r -> {
            purchasesId.add(r.getItem().get("id").toString());
            creditCodes.add(r.getItem().get("organizing_code").toString());
        });
        // 采购需求关联的拿地信息进行搜索拼装
        Map<String, ArrayList<Map<String, Object>>> projectsRes = this.getProjectsByPurchase(purchasesId);
        // 关联开发商指标进行搜索拼装
        Map<String, Map<String, Object>> metrics = this.getRelatedOrgMetrics(creditCodes);

        Set<String> haveAdded = remoteClueService.isAdded(purchasesId);

        res.getData().getList().forEach(r -> {
            Map<String, Object> map = developerService.setTjRes(r.getItem());

            try {
                String procurmentDeadline = r.getItem().get("end_time").toString();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date deadline = simpleDateFormat.parse(procurmentDeadline);

                if (deadline.getTime() > new Date().getTime()) {
                    map.put("status", "报名中");
                } else {
                    map.put("status", "已截止");
                }
            } catch (ParseException e) {
                map.put("status", "-");
            }

            ArrayList<Map<String, Object>> projects = projectsRes.get(r.getItem().get("id").toString());
            if (projects != null) {
                HashSet<String> citiesArray = new HashSet<>();
                HashSet<String> projectsArray = new HashSet<>();
                projects.forEach(p -> {
                    citiesArray.add(p.get("province").toString() + p.get("city"));
                    projectsArray.add(p.get("project_name").toString());
                });
                map.put("project_city", StringUtil.join(citiesArray, ","));
                map.put("projects", StringUtil.join(projectsArray, ","));
            }

            if (metrics.get(map.get("organizing_code").toString()) != null) {
                map.put("purchase_demand_cnt_1year", metrics.get(map.get("organizing_code").toString()).get("nearly_a_year_purchase_demand"));
                map.put("cooperation_enterprise_cnt", metrics.get(map.get("organizing_code").toString()).get("cooperation_enterprise"));
            }

            map.put("ower", MyStringUtil.ReplaceSpecifiedStr(0, 1, map.get("ower").toString(), "*", 2));
            map.put("ower_mobile", MyStringUtil.ReplaceSpecifiedStr(0, 3, map.get("ower_mobile").toString(), "*", 8));

            // 是否添加过
            int hasAdded = haveAdded.contains(map.get("id").toString()) ? 1 : 0;
            map.put("has_added", hasAdded);

            output.add(map);
        });
        result.setData(output);
        result.setTotal(res.getData().getTotal());
        return result;
    }

    protected Map<String, Map<String, Object>> getRelatedOrgMetrics(List<String> creditCodes) {
        List<Map<String, Object>> metrics = developerService.getMetricListByCreditCodeList(creditCodes);
        Map<String, Map<String, Object>> dict = new HashMap<>();

        metrics.forEach(m -> {
            dict.put(m.get("organizing_code").toString(), m);
        });

        return dict;
    }

    public List<Map<String, Object>> getPurchaseProjects(String purchaseId) {
        ArrayList<String> purchasesId = new ArrayList<String>() {{
            add(purchaseId);
        }};
        Map<String, ArrayList<Map<String, Object>>> data = getProjectsByPurchase(purchasesId);
        return data.getOrDefault(purchaseId, new ArrayList<>());
    }

    protected Map<String, ArrayList<Map<String, Object>>> getProjectsByPurchase(ArrayList<String> purchasesId) {
        String purchasesString = StringUtil.join(purchasesId, ",");
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_PROCUREMENT_PROJECT);
        dto.setPage(1);
        dto.setPage_size(1000);
        dto.addFilterDtos("purchase_id", BaseTjFilterDto.OPERATE_CONTAIN, purchasesString, DeveloperService.TABLE_PROCUREMENT_PROJECT, BaseTjFilterDto.ASSOCIATE_NONE);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);
        Map<String, ArrayList<Map<String, Object>>> projectsMap = new HashMap<>();

        if (res.getData() == null || res.getData().getList() == null) {
            return projectsMap;
        }

        res.getData().getList().forEach(p -> {
            ArrayList<Map<String, Object>> purchasePorjects = new ArrayList<>();
            if (projectsMap.get(p.getItem().get("purchase_id").toString()) != null) {
                purchasePorjects = projectsMap.get(p.getItem().get("purchase_id").toString());
            }

            purchasePorjects.add(p.getItem());
            projectsMap.put(p.getItem().get("purchase_id").toString(), purchasePorjects);
        });

        return projectsMap;
    }

    public Map<String, Object> getPurchaseByPurchaseId(String purchaseId) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_PROCUREMENT_REQUIREMENT);
        dto.setPage(1);
        dto.setPage_size(1);
        dto.addFilterDtos("id", BaseTjFilterDto.OPERATE_EQUAL, purchaseId, DeveloperService.TABLE_PROCUREMENT_REQUIREMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null || res.getData().getTotal() == 0) {
            return new HashMap<>();
        }

        return res.getData().getList().get(0).getItem();
    }

    public GetProcurementRequirementMobileRequestDto getProcurementRequirementMobile(String purchaseId) {
        Map<String, Object> purchase = getPurchaseByPurchaseId(purchaseId);
        GetProcurementRequirementMobileRequestDto getProcurementRequirementMobileRequestDto = new GetProcurementRequirementMobileRequestDto();
        getProcurementRequirementMobileRequestDto.setTel("");
        getProcurementRequirementMobileRequestDto.setName("");
        if (purchase.isEmpty()) {
            return getProcurementRequirementMobileRequestDto;
        }
        String phoneStr = purchase.getOrDefault("ower_mobile", "").toString();
        String sourceCode = purchase.getOrDefault("data_source_code", "").toString();

        if (phoneStr.length() > 0 && (sourceCode.equals("website_bid") || sourceCode.equals("trading_center"))) {

            if (purchase.get("ower") != null) {
                getProcurementRequirementMobileRequestDto.setName(MyStringUtil.spiltString(purchase.get("ower").toString()));
            }
            if (purchase.get("ower_mobile") != null) {
                getProcurementRequirementMobileRequestDto.setTel(MyStringUtil.spiltString(purchase.get("ower_mobile").toString()));
            }
            if (purchase.get("uid") != null) {
                getProcurementRequirementMobileRequestDto.setUid(purchase.get("uid").toString());
            }
        }

        return getProcurementRequirementMobileRequestDto;
    }

    public GetProcurementRequirementMobileRequestDto getProcurementRequirementAgentMobile(String purchaseId) {
        Map<String, Object> purchase = getPurchaseByPurchaseId(purchaseId);
        GetProcurementRequirementMobileRequestDto getProcurementRequirementMobileRequestDto = new GetProcurementRequirementMobileRequestDto();
        getProcurementRequirementMobileRequestDto.setTel("");
        getProcurementRequirementMobileRequestDto.setName("");
        if (purchase.isEmpty()) {
            return getProcurementRequirementMobileRequestDto;
        }
        String phoneStr = purchase.getOrDefault("agent_ower_mobile", "").toString();
        String sourceCode = purchase.getOrDefault("data_source_code", "").toString();
        if (phoneStr.length() > 0 && (sourceCode.equals("website_bid") || sourceCode.equals("trading_center"))) {
            getProcurementRequirementMobileRequestDto.setName(purchase.getOrDefault("agent_ower", "").toString());
            getProcurementRequirementMobileRequestDto.setTel(purchase.getOrDefault("agent_ower_mobile", "").toString());
        }

        return getProcurementRequirementMobileRequestDto;
    }
}